"""GitHub switch platform."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any, Dict

from openwrt_luci_rpc.exceptions import InvalidLuciLoginError  # pylint: disable=import-error

from homeassistant import config_entries, core
from homeassistant.core import HomeAssistant
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.entity import ToggleEntity  # pylint: disable=import-error
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.const import (  # pylint: disable=import-error
    CONF_MAC,
    CONF_NAME,
)
from homeassistant.helpers.entity import Entity  # pylint: disable=import-error
from homeassistant.helpers.dispatcher import (  # pylint: disable=import-error
    async_dispatcher_connect,
)

from .const import (
    DOMAIN,
    CONF_RPC,
    CONF_BLACKLIST,
    SIGNAL_STATE_UPDATED,
)

_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(minutes=30)


async def async_setup_entry(
    hass: core.HomeAssistant,
    config_entry: config_entries.ConfigEntry,
    async_add_entities,
) -> None:
    """Setup switches from a config entry created in the integrations UI."""
    _LOGGER.info(
        "Setup switches from a config entry created in the integrations UI.")
    _LOGGER.debug("Switch: config_entry ID ==> %s", config_entry.entry_id)
    _LOGGER.debug("Switch: config_entry Data ==> %s", dict(config_entry.data))
    _LOGGER.debug("Switch: config_entry Options ==> %s",
                  dict(config_entry.options))

    config = hass.data[DOMAIN][config_entry.entry_id]

    # 更新我们的配置以包含新的设备，并删除那些已删除的。
    if config_entry.options:
        config.update(config_entry.options)

    rpc = config.get(CONF_RPC)

    switchs = [LuciRuleSwitch(rpc, mac)
               for mac in config[CONF_BLACKLIST]]

    async_add_entities(switchs, update_before_add=True)


class LuciEntity(Entity):
    """ Base class for all entities. """

    def __init__(self, rpc, blacklist: Dict[str, Any] | None = None):
        """Initialize the entity."""
        self._rpc = rpc
        self.cfgname = blacklist[CONF_NAME]
        self.cfgmac = blacklist[CONF_MAC]
        self._is_on = False

        _LOGGER.debug("New entity: %s", self.cfgname)

        self.host = self._rpc.host

    async def async_added_to_hass(self):
        """Register update dispatcher."""
        async_dispatcher_connect(
            self.hass, SIGNAL_STATE_UPDATED, self.async_schedule_update_ha_state
        )

    @property
    def unique_id(self):
        return f"{self.host}_{self.cfgname}"

    @property
    def should_poll(self):
        """Return the polling state."""
        return True

    @property
    def assumed_state(self):
        """Return true if unable to access real state of entity."""
        return False

    @property
    def is_on(self):
        """Return true if switch is on."""
        return self._is_on


class LuciRuleSwitch(LuciEntity, ToggleEntity):
    """Representation of a Luci switch."""

    def __init__(self, rpc, blacklist: Dict[str, Any] | None = None):
        super().__init__(rpc, blacklist)

    @property
    def name(self):
        return "%s Rule" % (self.cfgname)

    @property
    def icon(self):
        """Return the icon."""
        return "mdi:fire"

    def turn_on(self, **kwargs):
        """Turn the switch on."""
        # await self.instrument.turn_on()
        _LOGGER.debug("Luci: %s turned on", self.cfgname)

        self._rpc.rpc_call("set", "firewall", self.cfgname, "enabled", "1")
        self._rpc.rpc_call("commit", "firewall")

        self.schedule_update_ha_state()

    def turn_off(self, **kwargs):
        """Turn the switch off."""
        # await self.instrument.turn_off()
        _LOGGER.debug("Luci: %s turned off", self.cfgname)

        self._rpc.rpc_call("set", "firewall", self.cfgname, "enabled", "0")
        self._rpc.rpc_call("commit", "firewall")

        self.schedule_update_ha_state()

    def update(self):
        """Update vesync device."""
        self._is_on = False
        try:
            cfg_value = self._rpc.rpc_call(
                'get', "firewall", self.cfgname, "enabled")
        except InvalidLuciLoginError:
            # 假设这意味着“enabled”键不存在;假设它表示True
            cfg_value = True
        except:
            _LOGGER.error("Cannot update rule %s", self.cfgname)
            return
        if (cfg_value is not None):
            _LOGGER.debug("Luci Rule get %s returned: %s",
                          self.cfgname, cfg_value)
            self._is_on = (cfg_value != "0")
